<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="站点:" prop="orgSNNo" class="merge-item" :table-form-merge="1.5">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="closeTree"
        />
        <div style="width: 120px; padding-left: 20px;">
          <el-checkbox v-model="query.option" label="包含下级" />
        </div>
      </el-form-item>
      <el-form-item :table-form-merge="2" label="结转日期:" clearable>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :picker-options="pickerOptions"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button v-permission="2" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <add ref="add" :tree-data="treeData" />
  </div>
</template>

<script>
  import {
    billCarrySelect,
    billCarryDelete
  } from '@/api'
  import { parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import Add from './components/addCarryOver'
  import dayjs from 'dayjs'
  export default {
    name: 'reconciliationCarryOver',
    components: {
      Add
    },
    data() {
      return {
        actionColWidth: 80,
        date: [],
        query: {
          orgSNNo: '',
          orgId: '',
          option: true
        },
        tableData: {
          total: 0,
          data: []
        },
        pickerOptions: {
          disabledDate(time) {
            const now = dayjs().format('YYYY-MM-DD')
            return time.getTime() >= dayjs(now).valueOf()
          }
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ]),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'orgName',
            label: '站点'
          },
          {
            prop: 'happendTime',
            label: '结转时间',
            render: (h, { row }) => <span>{ row.happendTime && parseTime(row.happendTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'createUser',
            label: '操作人'
          },
          {
            prop: 'remark',
            label: '备注'
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.status !== -1 && <el-link v-permission='3' underline={false} size='mini' type='danger' onClick={() => this.del(row, $index)}>
                    删除
                  </el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData()])
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        // 初始化企业
        this.query.orgSNNo = this.treeData[0].orgSNNo
        this.query.orgId = this.treeData[0].orgId
        // 初始化查询时间
        this.date = [dayjs(Date.now() - 8.64e7).format('YYYY-MM-DD 00:00:00'), dayjs(Date.now() - 8.64e7).format('YYYY-MM-DD 23:59:59')]
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.query.orgSNNo = value.orgSNNo
        this.query.orgId = value.orgId
      },
      // 清空所属机构
      closeTree(v) {
        this.query.orgSNNo = ''
        this.query.orgId = ''
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (!query.option) {
          delete query.orgSNNo
        } else {
          delete query.orgId
        }
        delete query.option
        if (this.date && this.date.length > 0) {
          query.happendTime = parseTime(this.date[0], '{y}-{m}-{d} {h}:{i}:{s}')
          query.happendTimeEnd = parseTime(this.date[1], '{y}-{m}-{d} {h}:{i}:{s}')
        }
        const res = await billCarrySelect(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询枚举
      //   async queryOptionsMap() {
      //     const [res] = await Promise.all([
      //       stockTransWin()
      //     ])
      //     this.gdStatusMap = JSON.parse(res.data.gdStatusMap) // 商品状态枚举
      //   },
      async add() {
        await this.$refs.add.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 不要删除
      del(row, index) {
        this.$confirm('确定要删除？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在删除',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          billCarryDelete({ carryOverCode: row.carryOverCode }).then(() => {
            this.tableData.data.splice(index, 1)
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.search()
          }).finally(() => {
            loading.close()
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
